#!/usr/bin/env python
# coding=UTF-8

from xml.dom.minidom import parse
import os

data_path = os.path.join(os.path.dirname(__file__),
                         '..', 'data')


def read_xml():

    xml = parse(data_path + '/customer.xml')
    root_node = xml.documentElement

    cus = root_node.getElementsByTagName('customer')
    for c in cus:
        id = c.getAttribute('id')
        name = c.getElementsByTagName("name")[0]
        phone = c.getElementsByTagName("phone")[0]
        print('id= {}, name= {}, phone= {}'.format(
            id, name.childNodes[0].data, phone.childNodes[0].data))


def write_xml():
    xml = parse(data_path + '/customer.xml')
    root_node = xml.documentElement

    # 新建一个customer节点
    cus_node = xml.createElement("customer")
    cus_node.setAttribute("id", "003")

    # 创建name节点,并设置textValue
    name_node = xml.createElement("name")
    name_value = xml.createTextNode("Yuri")
    # 把文本节点挂到name_node节点
    name_node.appendChild(name_value)
    cus_node.appendChild(name_node)

    # 创建phone节点,并设置textValue
    phone_node = xml.createElement("phone")
    phone_value = xml.createTextNode("32467")
    phone_node.appendChild(phone_value)  # 把文本节点挂到name_node节点
    cus_node.appendChild(phone_node)

    # 创建comments节点
    comments_node = xml.createElement("comments")
    comments_value = xml.createTextNode(
        "我是老板")
    comments_node.appendChild(comments_value)
    cus_node.appendChild(comments_node)

    root_node.appendChild(cus_node)

    with open(data_path + '/customer2.xml', 'w') as f:
        # 缩进 - 换行 - 编码
        xml.writexml(f, addindent='  ', encoding='utf-8')


def update_xml():
    xml = parse(data_path + '/customer.xml')
    root_node = xml.documentElement

    names = root_node.getElementsByTagName("name")
    names[0].childNodes[0].data = 'ChinaBoy'

    with open(data_path + '/customer.xml', 'w') as f:
        # 缩进 - 换行 - 编码
        xml.writexml(f, addindent='  ', encoding='utf-8')


if __name__ == '__main__':
    read_xml()
    write_xml()
    update_xml()
